// EStoreServer.java
package com.estore.network;

import com.estore.service.ProductService;
import com.estore.model.Product;

import java.io.*;
import java.net.*;
import java.util.List;

public class EStoreServer {
    private static final int PORT = 8888;
    private final ProductService productService;

    public EStoreServer() {
        this.productService = new ProductService();
    }

    public static void main() {
        EStoreServer server = new EStoreServer();
        server.start();
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.printf("服务器启动，监听端口: %d%n", PORT);

            while (true) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    System.out.printf("客户端连接: %s%n", clientSocket.getInetAddress());
                    handleClient(clientSocket);
                } catch (IOException e) {
                    System.err.printf("处理客户端连接时出错: %s%n", e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.printf("服务器启动失败: %s%n", e.getMessage());
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())) {

            // 读取客户端请求
            String request = (String) input.readObject();
            System.out.printf("收到客户端请求: %s%n", request);

            // 根据请求处理业务逻辑
            if ("GET ALL PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                output.writeObject(products);
                output.flush();
            } else {
                output.writeObject("未知请求");
                output.flush();
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("处理客户端请求时出错: %s%n", e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.printf("关闭客户端连接时出错: %s%n", e.getMessage());
            }
        }
    }
}
